package com.module.circle.ui.createCircle

import android.content.Intent
import android.net.Uri
import android.text.Editable
import android.util.Log
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.common.app.base.AppPictureSelectionActivity
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.circle.CircleListModel
import com.common.app.dialog.SelectAddressDialog
import com.common.app.utls.Constants
import com.common.app.utls.HeadTitleUtils
import com.common.app.utls.PermissionUtils
import com.common.base.app.extras.getShowMsg
import com.common.base.app.extras.loadRound
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.showToast
import com.common.base.app.extras.yes
import com.common.base.utils.AppUtils
import com.common.base.utils.LogUtils
import com.common.base.utils.SimpleTextWatcher
import com.common.base.utils.StatusBarUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.utils.MediaUtils
import com.module.circle.R
import com.module.circle.databinding.CircleActivityCreateCircleBinding
import java.io.File
import java.util.ArrayList

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/07/23
 * <p>
 * 描述：创建圈子界面
 * <p>
 * 修订历史：
 */
class CreateCircleActivity : AppPictureSelectionActivity<CircleActivityCreateCircleBinding, CreateCircleViewModel>(), View.OnClickListener,
    SelectAddressDialog.OnSelectAddressDialogClickListener {

    override fun getViewModel() = CreateCircleViewModel::class.java
    override fun getViewContentBinding() = CircleActivityCreateCircleBinding.inflate(layoutInflater)
    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true

    @Autowired(name = KeyBundle.BUNDLE_KEY)
    @JvmField
    var mBean: CircleListModel? = null

    private var imgId: Long = 0
    private var imgUrl: String? = null
    private var launcherResult: ActivityResultLauncher<Intent?>? = null

    private val selectAddressDialog by lazy { SelectAddressDialog(this) }

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, true)
        val headTitleUtils = HeadTitleUtils(this)
        headTitleUtils.setTitle(if (mBean == null)getString(R.string.circle_ac_create_circle_title) else getString(R.string.circle_ac_circle_info_edt_title))
        headTitleUtils.setLineStyle(10)

        // 注册需要写在onCreate或Fragment onAttach里，否则会报java.lang.IllegalStateException异常
        launcherResult = createActivityResultLauncher()
        initPictureStyle()
    }

    override fun initEvents() {
        super.initEvents()

        mViewContentBinding.bgActivityCity.setOnClickListener(onClick = this)
        mViewContentBinding.imgAddHead.setOnClickListener(onClick = this)
        mViewContentBinding.tvSaveBtn.setOnClickListener(onClick = this)


        mViewContentBinding.edtCircleName.addTextChangedListener(object : SimpleTextWatcher() {
            override fun afterTextChanged(s: Editable?) {
//                (s.toString().length >=10).yes {
//                    showToast("最多输入10个字符！")
//                }
                mViewContentBinding.tvCircleNameNum.text = "${s?.length.toString()}/10"
            }
        })

        mViewContentBinding.edtCircleIntroduction.addTextChangedListener(object : SimpleTextWatcher() {
            override fun afterTextChanged(s: Editable?) {
                mViewContentBinding.tvIntroductionNum.text = "${s?.length.toString()}/100"
            }
        })

        selectAddressDialog.setOnSelectAddressDialogClickListener(this)
    }

    override fun lazyInitData() {
        super.lazyInitData()

        mBean?.let {
            imgUrl = it.image_url
            mViewContentBinding.imgAddHead.loadRound(imgUrl,8)
            mViewContentBinding.edtCircleName.setText(it.name)
            mViewContentBinding.edtCircleIntroduction.setText(it.description)
//            mViewContentBinding.switchPublicCircle.initChecked(it.leader_id)
        }
        mViewContentBinding.tvSaveBtn.text = if (mBean == null)getString(R.string.circle_completed_creation_hint) else getString(R.string.common_confirm_modify_hint)

    }

    override fun onClick(v: View?) {
        when (v) {
            mViewContentBinding.imgAddHead-> {
                if (PermissionUtils.checkPermission(this)) {
                    selectFromAlbum(true, launcherResult, 1)
                }

            }
            mViewContentBinding.tvSaveBtn->{
                requestCreateCircles()
            }
            mViewContentBinding.bgActivityCity-> if (!selectAddressDialog.isShowing) selectAddressDialog.show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    /**
     * 创建ActivityResultLauncher
     *
     * @return
     */
    private fun createActivityResultLauncher(): ActivityResultLauncher<Intent?> {
        return registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            val resultCode = result.resultCode
            if (resultCode == RESULT_OK) {
                val selectList = PictureSelector.obtainSelectorList(result.data)
                analyticalSelectResults(selectList)
            } else if (resultCode == RESULT_CANCELED) {
                Log.i(TAG, "onActivityResult PictureSelector Cancel")
            }
        }
    }


    /**
     * 处理选择结果
     *
     * @param result
     */
    private fun analyticalSelectResults(result: ArrayList<LocalMedia>) {
        for (media in result) {
            if (media.width == 0 || media.height == 0) {
                if (PictureMimeType.isHasImage(media.mimeType)) {
                    val imageExtraInfo = MediaUtils.getImageSize(this, media.path)
                    media.width = imageExtraInfo.width
                    media.height = imageExtraInfo.height
                } else if (PictureMimeType.isHasVideo(media.mimeType)) {
                    val videoExtraInfo = MediaUtils.getVideoSize(this, media.path)
                    media.width = videoExtraInfo.width
                    media.height = videoExtraInfo.height
                }
            }
            Log.i(TAG, "文件名: " + media.fileName)
            Log.i(TAG, "是否压缩:" + media.isCompressed)
            Log.i(TAG, "压缩:" + media.compressPath)
            Log.i(TAG, "初始路径:" + media.path)
            Log.i(TAG, "绝对路径:" + media.realPath)
            Log.i(TAG, "是否裁剪:" + media.isCut)
            Log.i(TAG, "裁剪:" + media.cutPath)
            Log.i(TAG, "是否开启原图:" + media.isOriginal)
            Log.i(TAG, "原图路径:" + media.originalPath)
            Log.i(TAG, "沙盒路径:" + media.sandboxPath)
            Log.i(TAG, "水印路径:" + media.watermarkPath)
            Log.i(TAG, "视频缩略图:" + media.videoThumbnailPath)
            Log.i(TAG, "原始宽高: " + media.width + "x" + media.height)
            Log.i(TAG, "裁剪宽高: " + media.cropImageWidth + "x" + media.cropImageHeight)
            Log.i(TAG, "文件大小: " + media.size)
        }
        //上传obs
//        Constants.userBean?.let {
//            it.imageUrl = Uri.parse(LOCAL_FILE_SCHEME + result[0].sandboxPath).toString()
//        }
//        mViewContentBinding.imgAddHead.loadRound(Uri.parse(Constants.LOCAL_FILE_SCHEME + result[0].sandboxPath).toString(),8)//测试代码
        uploadImage(result[0].sandboxPath)
    }


    //开始上传图片
    private fun uploadImage(imgTemp: String) {
        imgId = 0
        val imgFile = File(imgTemp)
        if (imgFile.exists()) {
            showDialogLoading()
            mViewModel.uploadImage(imgFile,"image").observe(this) {

                dismissLoadingDialog()
                LogUtils.e("===>${it}")
                it.isSuccess().yes {
                    it.Data?.url?.let { urlIt->
                        imgId = it.Data?.id?:0
                        imgUrl= urlIt
                        mViewContentBinding.imgAddHead.loadRound(imgUrl,8)
                    }
                }
//                UserHelper.getUser()?.headImage = it ?: ""
//                mViewContentBinding.setUserAvatarIv.loadCircle(it, R.mipmap.ic_def_avatar)

            }
        }
    }


    private fun requestCreateCircles() {

        if (imgUrl.isNullOrEmpty()){
            showToast(getString(R.string.circle_create_lacking_head_hint))
            return
        }
        if (mViewContentBinding.edtCircleName.text.toString().trim().isNullOrEmpty()){
            showToast(getString(R.string.circle_create_lacking_name_hint))
            return
        }
        if (mViewContentBinding.edtCircleIntroduction.text.toString().trim().isNullOrEmpty()){
            showToast(getString(R.string.circle_create_lacking_des_hint))
            return
        }

//        if (mViewContentBinding.tvActivityCity.text.toString().trim().isNullOrEmpty()){
//            showToast(getString(R.string.circle_create_lacking_addr_hint))
//            return
//        }
        showDialogLoading()
        mViewModel.requestCreateCircles(mBean?.id?:0,mViewContentBinding.edtCircleName.text.toString().trim(),imgId,mViewContentBinding.switchPublicCircle.isChecked(),
            mViewContentBinding.tvActivityCity.text.toString().trim(), mViewContentBinding.edtCircleIntroduction.text.toString().trim()){
            showToast(it.getShowMsg())
        }.observe(this) {
            dismissLoadingDialog()
            it.isSuccess().yes {
                LiveEventBus.get(KeyEvents.KEY_CREATE_CIRCLE_EVENT).post(this)
                showToast(getString(R.string.circle_create_completed_hint))
                finish()
            }.otherwise {
                showToast(it.Message)
            }
        }
    }

    override fun onSuccessClick(agentName: String?, provinceCode: String?, mSubscript: Int) {
    }

    override fun onTypeNameClick(provinceValue: String?) {
        provinceValue?.let {
            it.replace(AppUtils.getString(R.string.common_not_select_hint),"")
            it.replace("null","")
            mViewContentBinding.tvActivityCity.text = it
        }
    }
}